﻿using System;
using System.Collections.Generic;

namespace Peak.Web.Controllers.Services
{
  public class BackLink
  {
    Stack<Uri> _returnUrls = new Stack<Uri>();
    private Uri _currentUrl;

    public void Push(Uri link)
    {
      if (_returnUrls.Count > 0 && _returnUrls.Peek().AbsolutePath == link.AbsolutePath)
      {
        _returnUrls.Pop();        
      }
      else if(_currentUrl != null && _currentUrl.AbsolutePath != link.AbsolutePath)
      {
        _returnUrls.Push(_currentUrl);      
      }
      _currentUrl = link;
    }

    public Uri Pop()
    {      
      return _currentUrl = _returnUrls.Pop();
    }

    public void Reset()
    {
      _currentUrl = null;
      _returnUrls.Clear();
    }

    public override string ToString()
    {
      string result = "";
      if(_currentUrl != null) 
        result = _currentUrl.AbsolutePath+"<br/><br/>";    

      foreach(Uri link in _returnUrls)
      {
        result += link.AbsolutePath + "<br/>";
      }
      return result;
    }
  }
}
